/*
 * Copyright WelinkSoft Ltd. (c) 2018.
 */

package com.xj.server;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(value = "databaseBackService")
@EnableScheduling
public class DatabaseBackService {
    @Resource(name = "dataBaseBackDao")
    DataBaseBackDaoImpl dataBaseBackDao;
    protected final Logger logger = Logger.getLogger(this.getClass().getSimpleName());
    @Value(value = "${backdatanames}")
    protected String backdatanames;
    @Value(value = "${backpath}")
    String backpath;
    @Value(value = "${backdays}")
    Long backdays;


    public void handBack(String backdatanames) {
        this.backdatanames = backdatanames;
        executeBack();
    }


    @Scheduled(cron = "${restartTask}")
    public void executeBack() {
        Boolean r;
        String[] dataname = null;
        if (StringUtils.isEmpty(this.backdatanames)) {
            String sql = "SELECT   name  AS dbname  FROM  master..sysdatabases  order  by name  asc ";
            List<Map> list = this.dataBaseBackDao.queryForlist(sql);
            dataname = new String[list.size()];
            for (int k = 0; k < list.size(); k++) {
                Map map = list.get(k);
                String dbname = map.get("dbname").toString();
                dataname[k] = dbname;
            }
        } else {
            dataname = backdatanames.split(",");
        }

        for (int j = 0; j < dataname.length; j++) {
            String db = dataname[j];
            String backname = db + "_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
            logger.info(new Date() + ("开始备份数据库：") + db);
            String ddate = new SimpleDateFormat("yyyyMMdd").format(new Date());
            File f = new File(backpath + File.separator + ddate);
            if (!f.isDirectory() || !f.exists())
                f.mkdirs();
            String sql = " backup database " + db + "  to   disk='" + f.getPath()
                    + File.separator + backname + ".bak'";
            System.out.println("sql=" + sql);
            try {
                dataBaseBackDao.execuSql(sql);
                deleteHistoryDB(backpath, backdays, db);
            } catch (Exception e) {
                logger.error(new Date() + "备份数据库失败,数据库为:" + db + "原因为" + e.getMessage());
            }
        }

    }

    public void deleteHistoryDB(String path, Long days, String db) {
        File foldpath = new File(path);
        File[] folds = foldpath.listFiles();
        for (int k = 0; k < folds.length; k++) {
            File fold = folds[k];
            if (fold.isDirectory()) {
                String foldname = fold.getName();
                try {
                    Date foldDate = new SimpleDateFormat("yyyyMMdd").parse(foldname);
                    Date d = new Date();
                    Long d1 = d.getTime();
                    Long d2 = foldDate.getTime();
                    if (d1 - d2 > (days * 24 * 3600 * 1000)) {
                        File[] backfiles = fold.listFiles();
                        for (int l = 0; l < backfiles.length; l++) {
                            File backfile = backfiles[l];
                            int pos = backfile.getName().lastIndexOf("_");
                            String oldfile = backfile.getName().substring(0, pos);
                            if (db.toLowerCase().equals(oldfile.toLowerCase()))
                                backfile.delete();
                        }
                        //删除文件夹
                        File[] fs = fold.listFiles();
                        if (fs.length == 0)
                            fold.delete();
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}
